<template>
    <view class="flex-1 flex flex-column overflow-auto pb-10 grid-gap-6">
        <template v-if="$helper.isWechat() && WEBCONFIG?.wx_state && nav === 'wechat'">
            <view class="flex-1 flex flex-column flex-x-center px-10">
                <!-- #ifndef MP-WEIXIN -->
                <view class="flex flex-center flex-column" v-if="props.showLogo">
                    <image :src="WEBCONFIG?.web_logo" v-if="WEBCONFIG?.web_logo" class="logo"></image>
                    <image src="@/static/logo.png" v-else class="logo"></image>
                </view>
                <!-- #endif -->
                <view class="flex-1 flex flex-column grid-gap-4">
                    <!-- #ifdef H5 -->
                    <view class="flex flex-center">
                        <button class="btn-primary btn-round" @tap="wxLogin">微信公众号一键登录</button>
                    </view>
                    <!-- #endif -->
                    <!-- #ifdef MP-WEIXIN -->
                    <view class="flex-1 flex flex-column flex-x-center px-10 grid-gap-6">
                        <view class="flex flex-center px-4 flex-column">
                            <button open-type="chooseAvatar" @chooseavatar="chooseavatar" class="avatar-btn bg">
                                <image v-if="form.avatar" :src="form.avatar" class="avatar" />
                                <image v-else-if="WEBCONFIG?.default_avatar" :src="WEBCONFIG?.default_avatar"
                                    class="avatar" />
                                <uni-icons v-else type="person-filled" size="30" color="var(--xl-primary)" />
                            </button>
                            <view class="h8 text-grey pt-2 font-weight-600">头像</view>
                        </view>
                        <view class="bg rounded-round flex flex-center px-4">
                            <view class="w-30px">
                                <uni-icons type="person" size="30" color="var(--xl-primary)"></uni-icons>
                            </view>
                            <input type="nickname" v-model="form.nickname" @blur="nicknameBlur"
                                class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary" placeholder="昵称"
                                placeholder-class="h8 text-grey" @confirm="submit">
                        </view>
                        <view class="flex flex-center">
                            <button class="flex-1 btn-primary btn-round" @tap="submit()">快速登录</button>
                        </view>
                    </view>
                    <!-- #endif -->
                    <view class="flex flex-center grid-gap-6">
                        <view class="h9 text-primary py-4" @tap="nav = 'user'">账号密码登录</view>
                        <view class="h9 text-primary py-4" @tap="nav = 'mobile'">手机号登录</view>
                    </view>
                    <view class="flex flex-center" @tap="form.agreement = !form.agreement">
                        <uni-icons type="circle-filled" v-if="form.agreement" color="var(--xl-primary)" />
                        <uni-icons type="circle" v-else color="var(--xl-primary)" />
                        <view class="h9 text-dark-light-3 pl-2">请阅读并同意</view>
                        <view class="h9 text-primary ml-2" @tap.stop="openAgreement">《用户协议》</view>
                    </view>
                </view>
            </view>
        </template>
        <template v-else>
            <view class="flex-1 flex flex-column flex-x-center px-10 grid-gap-6" v-if="nav === 'user'">
                <view class="bg rounded-round flex flex-center px-4">
                    <view class="w-30px">
                        <uni-icons type="phone" size="30" color="var(--xl-primary)"></uni-icons>
                    </view>
                    <input ref="mobileRef" v-model="mobile" type="tel"
                        class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary" placeholder="手机号"
                        placeholder-class="h8" maxlength="13" @input="formatMobile" @confirm="submit">
                    <view class="w-30px">
                        <uni-icons v-if="mobile" type="close" size="30" color="var(--xl-primary)"
                            @tap="mobile = ''"></uni-icons>
                    </view>
                </view>
                <view class="bg rounded-round flex flex-center px-4">
                    <view class="w-30px">
                        <uni-icons type="locked" size="30" color="var(--xl-primary)"></uni-icons>
                    </view>
                    <input v-model="form.password" :type="passwordType" :password="passwordType === 'password'"
                        class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary" placeholder="密码" placeholder-class="h8"
                        @confirm="submit">
                    <view class="w-30px">
                        <uni-icons type="eye-slash" size="30" color="var(--xl-placeholder)"
                            v-if="passwordType === 'password'" @tap="passwordType = 'text'"></uni-icons>
                        <uni-icons type="eye" size="30" color="var(--xl-placeholder)" v-else
                            @tap="passwordType = 'password'"></uni-icons>
                    </view>
                </view>
            </view>
            <view class="flex-1 flex flex-column flex-x-center px-10 grid-gap-6" v-else-if="nav === 'mobile'">
                <view class="bg rounded-round flex flex-center px-4">
                    <view class="w-30px">
                        <uni-icons type="phone" size="30" color="var(--xl-primary)"></uni-icons>
                    </view>
                    <input ref="mobileRef" v-model="mobile" type="tel"
                        class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary" placeholder="手机号"
                        placeholder-class="h8" maxlength="13" @input="formatMobile" @confirm="submit">
                    <view class="w-30px">
                        <uni-icons v-if="mobile" type="close" size="30" color="var(--xl-primary)"
                            @tap="mobile = ''"></uni-icons>
                    </view>
                </view>
                <view class="bg rounded-round flex flex-center pl-4 overflow-hidden" v-if="WEBCONFIG?.imgcode">
                    <view class="w-30px">
                        <uni-icons type="image" size="30" color="var(--xl-primary)"></uni-icons>
                    </view>
                    <input v-model="form.imgcode" type="text" class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary"
                        placeholder="图形验证码" placeholder-class="h8" maxlength="6" @confirm="submit">
                    <image :src="captchaUrl" class="captcha-image flex-1" mode="scaleToFill" @tap="getCaptchaUrl" />
                </view>
                <view class="bg rounded-round flex flex-center px-4">
                    <view class="w-30px">
                        <uni-icons type="email" size="30" color="var(--xl-primary)"></uni-icons>
                    </view>
                    <input v-model="form.vcode" type="tel" class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary"
                        placeholder="验证码" placeholder-class="h8" maxlength="6" @confirm="submit">
                    <view class="h9 font-weight-600" @tap="getVcode"
                        :class="vcodeBtn.disabled ? 'text-placeholder' : 'text-primary'">{{ vcodeBtn.text }}</view>
                </view>
            </view>
            <!-- #ifdef MP-WEIXIN -->
            <view class="flex-1 flex flex-column flex-x-center px-10 grid-gap-6" v-else-if="nav === 'auth'">
                <view class="flex flex-center px-4 flex-column bg p-4 rounded-4 grid-gap-2">
                    <text class="py-4 text-placeholder">是否使用当前授权用户登录？</text>
                    <image v-if="authInfo.headimg" :src="authInfo.headimg" class="rounded-round"
                        style="width: 100rpx;height: 100rpx;" />
                    <text class="h8 font-weight-600">{{ authInfo.nickname }}</text>
                </view>
                <view class="flex flex-center">
                    <button class="btn-primary btn-round px-10" @tap="submit">确认登录</button>
                </view>
            </view>
            <!-- #endif -->
            <view class="flex flex-column grid-gap-4">
                <view class="flex flex-center" v-if="['user', 'mobile'].includes(nav)">
                    <button class="btn-primary btn-round px-10" @tap="submit">登录/注册</button>
                </view>
                <view class="flex flex-center grid-gap-6">
                    <view class="h9 text-primary py-4" @tap="nav = 'user'" v-if="nav != 'user'">账号密码登录</view>
                    <view class="h9 text-primary py-4" @tap="nav = 'mobile'" v-if="nav != 'mobile'">验证码登录</view>
                    <!-- #ifdef H5 -->
                    <view class="h9 text-primary py-4" @tap="nav = 'wechat'"
                        v-if="$helper.isWechat() && WEBCONFIG?.wx_state">微信公众号一键登录</view>
                    <!-- #endif -->
                    <!-- #ifdef MP-WEIXIN -->
                    <view class="h9 text-primary py-4" v-if="WEBCONFIG?.wx_applet_state && nav != 'auth' && !authInfo.code"
                        @tap.stop="nav = 'wechat'">微信快速登录
                    </view>
                    <view class="h9 text-primary py-4" v-else-if="WEBCONFIG?.wx_applet_state && nav != 'auth' && authInfo.code"
                        @tap.stop="nav = 'auth'">授权登录</view>
                    <!-- #endif -->
                </view>
                <view class="flex flex-center mt-2" @tap="form.agreement = !form.agreement">
                    <uni-icons type="circle-filled" v-if="form.agreement" color="var(--xl-primary)" />
                    <uni-icons type="circle" v-else color="var(--xl-primary)" />
                    <view class="h9 text-dark-light-3 pl-2">请阅读并同意</view>
                    <view class="h9 text-primary ml-2" @tap.stop="openAgreement">《用户协议》</view>
                </view>
            </view>
        </template>
    </view>
</template>

<script setup lang="ts">
import { ref, defineProps, onMounted } from "vue";
import { $http, $api, $message, $page, $helper } from "@/utils";
import { $ResponseCode } from "@/utils/const/env";
import { useWebConfigStore, useUserStore, useRefs } from "@/stores";
const props = withDefaults(defineProps<{
    showLogo?: boolean,
}>(), {
    showLogo: true
});
const WebConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(WebConfigStore);
const UserStore = useUserStore();
const { USERINFO } = useRefs(UserStore);
const nav = ref('mobile');
const mobile = ref('');
const captchaUrl = ref('');
const form = ref({
    mobile: '',
    imgcode: '',
    vcode: '',
    code: '',
    avatar: '',
    nickname: '',
    password: '',
    agreement: false
});
const authInfo = ref({
    code: '',
    nickname: '',
    headimg: ''
});
const vcodeBtn = ref({
    text: '获取验证码',
    disabled: false
});
const passwordType = ref('password');
const emit = defineEmits(['success', 'fail', 'wx-login']);
const nicknameBlur = (e: any) => {
    form.value.nickname = e.detail.value;
}
const show = () => {
    // #ifdef H5
    form.value.agreement = true;
    // #endif

    // #ifdef MP-WEIXIN
    uni.showLoading({
        title: '登录中...',
        mask: true
    })
    wx.login({
        success: (res: any) => {
            if (res.code) {
                form.value.code = res.code;
                $api.Login.wechatMPCode({ code: res.code }).then((res: any) => {
                    authInfo.value.code = res.data.code;
                    authInfo.value.nickname = res.data.nickname;
                    authInfo.value.headimg = res.data.headimg;
                    nav.value = 'auth';
                }).catch((err: any) => {
                    if (err.code === $ResponseCode.NEED_LOGIN) {
                        nav.value = 'mobile';
                    }
                }).finally(() => {
                    uni.hideLoading();
                })
            } else {
                uni.hideLoading();
                uni.showModal({
                    title: '提示',
                    content: '登录失败，' + res.errMsg,
                    showCancel: false,
                    success: () => {
                        emit('fail');
                    }
                })
            }
        },
        fail: (err: any) => {
            uni.hideLoading();
            uni.showModal({
                title: '提示',
                content: '微信登录失败，' + err.errMsg,
                showCancel: false,
                success: () => {
                    emit('fail');
                }
            })
        }
    })
    // #endif
}
const formatMobile = () => {
    let phoneNumber = mobile.value.replace(/\D/g, '');
    form.value.mobile = phoneNumber;
    // 格式化手机号：188 8888 8888
    if (phoneNumber.length > 3 && phoneNumber.length < 8) {
        phoneNumber = phoneNumber.replace(/(\d{3})(\d{1,4})/, '$1 $2');
    } else if (phoneNumber.length >= 8) {
        phoneNumber = phoneNumber.replace(/(\d{3})(\d{1,4})(\d{1,4})/, '$1 $2 $3');
    }
    mobile.value = phoneNumber;
}
const restForm = () => {
    mobile.value = '';
    form.value.mobile = '';
    form.value.vcode = '';
}
const submit = () => {
    if (!form.value.agreement) {
        $message.error('请先阅读并同意用户协议');
        return;
    }
    uni.showLoading({
        title: '登录中...',
        mask: true
    })
    switch (nav.value) {
        case 'mobile':
            $api.Login.vcode(form.value).then((res: any) => {
                $message.success('登录成功');
                UserStore.setUserInfo(res.data).then(() => {
                    restForm();
                    emit('success');
                })
            }).catch((err: any) => {
                $message.error(err.msg);
            }).finally(() => {
                uni.hideLoading();
            })
            break;
        case 'user':
            $api.Login.login(form.value).then((res: any) => {
                $message.success('登录成功');
                UserStore.setUserInfo(res.data).then(() => {
                    restForm();
                    emit('success');
                })
            }).catch((err: any) => {
                $message.error(err.msg);
            }).finally(() => {
                uni.hideLoading();
            })
            break;
        case 'wechat':
            // #ifdef MP-WEIXIN
            $api.Login.wechatMP(form.value).then((res: any) => {
                $message.success('登录成功');
                UserStore.setUserInfo(res.data).then(() => {
                    restForm();
                    emit('success');
                })
            }).catch((err: any) => {
                $message.error(err.msg);
            }).finally(() => {
                uni.hideLoading();
            })
            // #endif
            break;
        case 'auth':
            // #ifdef MP-WEIXIN
            $api.Login.wechatMPCode({
                code: form.value.code,
                confirm: true
            }).then((res: any) => {
                $message.success('登录成功');
                UserStore.setUserInfo(res.data).then(() => {
                    restForm();
                    emit('success');
                })
            }).catch((err: any) => {
                if (err.code === $ResponseCode.NEED_LOGIN) {
                    uni.showModal({
                        title: '提示',
                        content: '登录失败，' + err.msg,
                        showCancel: false,
                        success: () => {
                            emit('fail');
                        }
                    })
                }
            }).finally(() => {
                uni.hideLoading();
            })
            // #endif
            break;
    }
}
const getVcode = () => {
    if (vcodeBtn.value.disabled) { return; }
    $api.Login.getVcode({
        mobile: form.value.mobile,
        imgcode: form.value.imgcode
    }).then(() => {
        vcodeBtn.value.disabled = true;
        let time = 60;
        const timer = setInterval(() => {
            vcodeBtn.value.text = `${time}s`;
            time--;
            if (time < 0) {
                clearInterval(timer);
                vcodeBtn.value.text = '获取验证码';
                vcodeBtn.value.disabled = false;
            }
        }, 1000)
    }).catch((err: any) => {
        $message.error(err.msg);
    });
}
const getCaptchaUrl = () => {
    captchaUrl.value = $http.baseURL + 'Login/captcha?' + Math.random();
}
const chooseavatar = (e) => {
    uni.showLoading({
        title: '上传中...',
        mask: true
    })
    $api.Upload.upload({
        filePath: e.detail.avatarUrl,
        name: 'file'
    }).then((res: any) => {
        form.value.avatar = res.data.url;
    }).catch((err: any) => {
        $message.error(err.msg);
    }).finally(() => {
        uni.hideLoading();
    })
}
const openAgreement = () => {
    form.value.agreement = true;
    $page.open('/pages/article/content?alias=user_agreement');
}
const wxLogin = () => {
    emit('wx-login')
}
onMounted(() => {
    captchaUrl.value = $http.baseURL + 'Login/captcha';
    // #ifdef H5
    if ($helper.isWechat() && WEBCONFIG.value?.wx_state) {
        nav.value = 'wechat';
    }
    // #endif
    // #ifdef MP-WEIXIN
    if ($helper.isWechat() && WEBCONFIG.value?.wx_applet_state) {
        nav.value = 'wechat';
    }
    // #endif
})
defineExpose({
    show
})
</script>

<style lang="scss" scoped>
.w-30px {
    width: 30px;
}

.w-100px {
    width: 100px;
}

.captcha-image {
    height: 60px;
}

.avatar-btn {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
    }
}

.logo {
    height: 200rpx;
    width: 200rpx;
    margin-bottom: 30rpx;
    border-radius: 30rpx;
}
</style>